#include "stdafx.h"
#include "julianDate.h"

double convertDateToJulian(sDate date)
{
    double a = (double)(14.0 - date.month) / 12.0;
    double y = date.year + 4800 - a;
    double m = date.month + 12.0 * a - 3;
    double jdn = date.day + (double)(153 * m + 2) / 5.0 + 365.0 * y + y / 4.0 - y / 100.0 + y / 400.0 - 32045;
    return (double)jdn + (double)(date.hour - 12.0) / 24.0 + (double)date.minute / 1440.0 + (double)date.second / 86400.0;
    
}

sDate convertJulianToDate(double julian)
{
    sDate date;
    julian += 0.5;
    double j = julian + 32044;
    double g = j / 146097.0;
    int dg = (int)j % 146097;
    double c = ((dg / 36524.0 + 1) * 3.0) / 4.0;
    double dc = dg - c * 36524.0;
    double b = dc / 1461.0;
    int db = (int)dc % 1461;
    double a = (db / 365.0 + 1) * 3.0 / 4.0;
    double da = db - a * 365.0;
    double y = g * 400 + c * 100 + b * 4 + a;
    double m = (double)(da * 5 + 308) / 153.0 - 2;
    double d = da - (m + 4) * 153.0 / 5.0 + 122;
#ifdef DEBUG
            std::cout << "julian = " << julian << std::endl;
    
            std::cout << "j = " << j << std::endl;
    
            std::cout << "g = " << g << std::endl;
    
            std::cout << "dg = " << dg << std::endl;
    
            std::cout << "c = " << c << std::endl;
    
            std::cout << "dc = " << dc << std::endl;
    
            std::cout << "b = " << b << std::endl;
    
            std::cout << "db = " << db << std::endl;
    
            std::cout << "a = " << a << std::endl;
    
            std::cout << "da = " << da << std::endl;
    
            std::cout << "y = " << y << std::endl;
    
            std::cout << "m = " << m << std::endl;
    
            std::cout << "d = " << d << std::endl;
#endif
    date.year = y - 4800 + (double)(m + 2) / 12.0;
    date.month = (unsigned char)((int)(m + 2) % 12 + 1);
    date.day = d + 1;
    return date;
}